package org.example.gmalllogger.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.constances.CommonConstants;
import lombok.extern.log4j.Log4j;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Log4j
public class LoggerController {
    //只要pom.xml引入了spring-kafka的依赖框架,容器会自动创建一个KafkaTemplate<?,?>对象
    //直接顶上Autowired注解就行
    @Autowired
    private KafkaTemplate<String, String> kafkaProducer;

    @RequestMapping(value = "/log1")
    public Object handle(String log1) {
        //将接收的log请求使用fastjson转换为java对象
        JSONObject jsonObject = JSON.parseObject(log1);
        //添加ts当前服务器时间
        jsonObject.put("ts", System.currentTimeMillis());
        //设置log级别,本来应该new logger对象,
        // 但使用lombok插件在类上顶注解SLF4j,会自动在容器中帮你创建对象,等价于Logger log= Logger.getLogger(LoggerController.class);
        log.info(jsonObject.toString());

        //将log日志按照类别生产至kafka的不同主题
        if ("event".equals(jsonObject.getString("type"))) {
            kafkaProducer.send(CommonConstants.KAFKA_EVENT_LOG,jsonObject.toString());
        }else{
            kafkaProducer.send(CommonConstants.KAFKA_START_LOG,jsonObject.toString());
        }
        return "success";
    }
    @RequestMapping(value = "/hello")//测试,处理/hello的请求
    public String handle1() {
        System.out.println("hello");
        return "success";
    }
}
